package com.bookmanagement.config;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器，统一处理应用程序抛出的异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 RuntimeException 异常，返回 JSON 格式的错误响应
     * @param ex 异常对象
     * @return 包含错误信息的 JSON 响应
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException ex) {
        ex.printStackTrace();
        Map<String, Object> response = new HashMap<>();
        response.put("code", 1); // 错误码，1 表示失败
        response.put("message", ex.getMessage()); // 错误消息，例如“用户名或密码错误”
        response.put("data", null); // 数据字段置空
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); // 返回 400 状态码
    }


    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<Map<String, Object>> handleDataIntegrityViolationException(DataIntegrityViolationException ex) {
        ex.printStackTrace();
        Map<String, Object> response = new HashMap<>();
        response.put("code", 1);
        response.put("message", "删除失败：该用户存在关联的借阅记录，不能删除！");
        response.put("data", null);
        return new ResponseEntity<>(response, HttpStatus.CONFLICT); // 409 冲突
    }

}